﻿
package extremefx.ui {
	import extremefx.events.MouseEventArgs;
	import extremefx.geom.Size;
	import extremefx.ui.styles.UIStates;
	
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFieldType;	

	/**
	 * @author Marcelo Volmaro
	 */
	public class ListItem extends AbstractListItem {
		private var _bs:ButtonSprite;
		private var _oldState:uint;
		private var _tf:TextField;
		private var _minItemSize:Size;

		public function ListItem(pParams:UIParameters) {
			super(pParams);
			initStyle("ListItem", pParams);
			
			var tf:TextField = _tf = new TextField();
			tf.autoSize = TextFieldAutoSize.NONE;
			
			tf.selectable = false;
			tf.type = TextFieldType.DYNAMIC;
			tf.condenseWhite = true;
			
			tf.x = _style.padding.left;
			tf.y = _style.padding.top;
			_style.textFormat.applyToTextfield(tf);
			
			_visualUI.addChild(tf);
			
			_bs = new ButtonSprite(_visualUI);
			_bs.onRollOver.add(_rollOver);
			_bs.onRollOut.add(_rollOut);
			_bs.onReleaseOutside.add(_rollOut);
			_bs.onDragOut.add(_rollOut);
			
			_bs.onPress.add(_press);
			_bs.onDragOver.add(_press);
			_bs.onRelease.add(_release);
			
			_focusVisual = false;
			_minItemSize = new Size(0, _style.getRawProperty("minHeight"));
			
			tabEnabled(false);
		}

		override public function set text(pName:String):void{
			_tf.htmlText = super.name = pName;
		}

		override public function set selected(pSelected:Boolean):void{
			super.selected = pSelected;
			invalidate();
		}
		
		private function _rollOut(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.NORMAL);
		}
		
		private function _rollOver(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.HOVER);
		}
		
		private function _press(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.ACTIVE);
		}
		
		private function _release(pSender:ButtonSprite, pArgs:MouseEventArgs):void{
			_setView(UIStates.NORMAL);
			onSelect(this);
		}
		
		override public function setState(pState:uint):void {
			_setView(pState);
		}
		
		private function _setView(pState:uint, pForce:Boolean = false):void{
			pState = _getState(pState, selected);
			
			if (_oldState == pState && !pForce) return;
			_oldState = pState;
			_style.getPseudoStyle(pState).textFormat.applyToTextfield(_tf);
			
			_setDecoState(pState, _width, _height);
		}
		
		protected override function _draw():void {
			_bs.enabled = _enabled;
			_setView(_oldState, true);

			_tf.width = _style.padding.getWidth(_width);
			_tf.height = _style.padding.getHeight(_height);
		}
		
		override public function get minimumSize():Size {
			return _minItemSize;
		}

		override public function dispose():void {
			if (_disposing) return;
			super.dispose();
			
			_bs.dispose();
		}
	}
}
